class DBAccess

  def initialize(conf)
    @dbconf = conf[:database]
    self.connect
  end

  def connect
      @dbh = DBI.connect(@dbconf[:url].untaint, @dbconf[:user], @dbconf[:pass])
  end

  def ensure_connection
    self.connect if !active(@dbh)
  end

  def ensure
    self.connect if !active(@dbh)
    yield @dbh
  end

  def active(conn)
    conn.execute("SELECT 1") 
    true 
  rescue DBI::DatabaseError 
    false 
  end 

  def conn; @dbh; end
  
  def save_inbox(data)
    @dbh.do("INSERT INTO inbox SET body=?, msisdn=?, smsc=?, charset=?", data[:body], data[:msisdn], data[:smsc], data[:charset]) 
  end

  def get_pattern(pattern)
    @dbh.select_one("SELECT name from patterns WHERE format  LIKE ?", pattern)
  end

  def get_smsc(name)
    @dbh.select_one("SELECT id,name from smsc WHERE name = ?", name)
  end

  def get_tmpl(type)
    @dbh.select_one("SELECT template from templates WHERE name LIKE ? AND activate=1", type)
  end

end
